import { Entity, System, World } from '@ecs/index'
import { createObstacles } from '../entities'
import { Position, Size } from '../components'

/**
 * 障碍物系统
 * @description 循环生成销毁障碍物
 */
export class ObstacleSystem extends System {
  constructor(private readonly canvas: HTMLCanvasElement) {
    super()
  }

  public update(world: World): void {
    // 1.无障碍物：创建障碍物
    const [upObstacles1] = this.getObstacleData(world)
    if (!upObstacles1) {
      createObstacles(world)
      return
    }

    // 2.当前第1组障碍物x坐标 + 障碍物自身宽度 <= 0 且 总共2组障碍物：移除当前第1组障碍物
    const [upObstacles2, downObstacles2, position2, size2] =
      this.getObstacleData(world)
    if (position2.x + size2.w <= 0 && upObstacles2.length === 2) {
      world.removeEntity(upObstacles2[0])
      world.removeEntity(downObstacles2[0])
    }

    // 3.当前第1组障碍物x坐标 < (屏幕宽度 - 当前第1组障碍物宽度)/2 且 总共1组障碍物：新建第2组障碍物
    const [upObstacles3, , position3, size3] = this.getObstacleData(world)
    if (
      position3.x < (this.canvas.width - size3.w) / 2 &&
      upObstacles3.length === 1
    ) {
      createObstacles(world)
    }
  }

  /**
   * 获取障碍物数据
   * @param world 世界实例
   * @returns
   */
  private getObstacleData(world: World): [Entity[], Entity[], Position, Size] {
    const upObstacles = world.findNameWithEntities('upObstacle')
    const downObstacles = world.findNameWithEntities('downObstacle')
    if (!upObstacles.length) {
      return [null, null, null, null]
    }
    const componentMap = world.findEntityWithComponents(upObstacles[0])
    const position = componentMap.get(Position)
    const size = componentMap.get(Size)
    return [upObstacles, downObstacles, position, size]
  }

  public destory(): void {}
}
